package com.geniusk.app.controller;

import cn.hutool.json.JSONUtil;
import com.geniusk.common.core.JSONResult;
import com.geniusk.file.utils.MinioUtil;
import com.geniusk.security.core.LoginUser;
import com.geniusk.security.utils.SecurityUtil;
import com.geniusk.security.utils.TokenUtil;
import com.geniusk.system.model.bo.profile.UpdateProfileBO;
import com.geniusk.system.model.bo.user.UpdateUserBO;
import com.geniusk.system.model.pojo.User;
import com.geniusk.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * APP个人信息接口
 */
@RestController
@RequestMapping("/app/profile")
public class AppProfileController {

    @Autowired
    private MinioUtil minioUtil;

    @Autowired
    private UserService userService;

    @Autowired
    private TokenUtil tokenUtil;

    /**
     * 查询个人信息
     */
    @GetMapping("/selectProfile")
    public JSONResult selectProfile(){
        Long userId = SecurityUtil.getUserId();
        User user = userService.selectUserById(userId);
        Map<String,Object> result = new HashMap<>();
        result.put("user",user);
        return JSONResult.ok(result);
    }

    /**
     * 修改个人信息
     */
    @PostMapping("/updateProfile")
    public JSONResult updateProfile(@Valid @RequestBody UpdateProfileBO updateProfileBO){
        User user = JSONUtil.parse(updateProfileBO).toBean(User.class);
        user.setUpdateBy(SecurityUtil.getUsername());
        int row = userService.updateProfile(user);
        if(row > 0){
            LoginUser loginUser = SecurityUtil.getLoginUser();
            loginUser.setName(updateProfileBO.getName());
            tokenUtil.saveTokenCache(loginUser);
        }
        return JSONResult.ok();
    }

    /**
     * 头像上传
     */
    @PostMapping("/uploadAvatar")
    public JSONResult uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            // 上传并返回访问地址
            String avatarUrl = minioUtil.uploadFile(file);
            Map<String,Object> result = new HashMap<>();
            result.put("avatarUrl",avatarUrl);
            userService.updateAvatar(SecurityUtil.getUserId(),avatarUrl);
            return JSONResult.ok(result);
        } catch (Exception e) {
            return JSONResult.errorMsg(e.getMessage());
        }
    }
}
